<?php

namespace Havoo\Core;

use ReflectionMethod;
use RuntimeException;
use Exception;

class Core
{

    public function run()
    {
        $this->init();
        $this->route();
    }

    public function init()
    {
        startSession();
    }

    public function route()
    {
        $controllerName = 'Index';
        $action = 'index';
        $params = [];
        $isAdmin = false;

        if (!empty($_GET['__url'])) {
            $urlArray = explode('/', trim($_GET['__url'], '/'));

            $controllerName = ucfirst(array_shift($urlArray));
            $action = empty($urlArray[0]) ? 'index' : array_shift($urlArray);

            while ($paramName = array_shift($urlArray)) {
                if ($paramValue = array_shift($urlArray)) {
                    $params[$paramName] = $paramValue; 
                } else {
                    break;
                }
            }
        }

        $controller = 'App\Controllers\\' . $controllerName . 'Controller';
        if (!method_exists($controller, $action)) {
            throw new Exception('method not exists: ' . $controller . '.' . $action, 500);
        }
        $method = new ReflectionMethod($controller, $action);
        $methodParams = $method->getParameters();
        $args = [];
        foreach ($methodParams as $param) {
            if (isset($params[$param->getName()])) {
                $args[] = $params[$param->getName()];
            } elseif ($param->isDefaultValueAvailable()) {
                $args[] = $param->getDefaultValue();
            } 
        }
        if (count($args) == $method->getNumberOfParameters()) {
            $method->invokeArgs(new $controller($controllerName, $action, $args));
        } else {
            throw new RuntimeException('miss params');
        }
    }

}

